<template>
  <div class="custom-form">
    <el-row :gutter="15">
      <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
      
        <el-col :span="8" v-if="hasFormPermission('F_DocunNumber')">
          <el-form-item label="单据编号" prop="F_DocunNumber">
            <el-input v-model="formData['F_DocunNumber']" placeholder="单据编号"
              :disabled="hasDisabledPermission('F_DocunNumber',undefined)"
              :readonly="!hasEditPermission('F_DocunNumber',true)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="hasFormPermission('F_DocumentDate')">
          <el-form-item label="单据日期" prop="F_DocumentDate">
            <el-date-picker :disabled="hasDisabledPermission('F_DocumentDate',false)"
              :readonly="!hasEditPermission('F_DocumentDate',false)" v-model="formData['F_DocumentDate']"
              format="yyyy-MM-dd" value-format="yyyy-MM-dd" :style="{width: '100%'}" placeholder="请选择单据日期"
              clearable></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="hasFormPermission('F_ChargePeople')">
          <el-form-item label="经办人员" prop="F_ChargePeople">
            <el-input v-model="formData['F_ChargePeople']" placeholder="请输入经办人员"
              :disabled="hasDisabledPermission('F_ChargePeople',false)"
              :readonly="!hasEditPermission('F_ChargePeople',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="hasFormPermission('F_DeliveryUnit')">
          <el-form-item label="供货单位" prop="F_DeliveryUnit">
            <el-select v-model="formData.F_DeliveryUnit" placeholder="请选择供货单位"
              :disabled="hasDisabledPermission('F_DeliveryUnit',false)"
              :readonly="!hasEditPermission('F_DeliveryUnit',undefined)" filterable clearable
              :style="{width: '100%'}" remote :remote-method="getF_DeliveryUnitOptions"
              @change="handlerSelectF_DeliveryUnit" :loading="F_DeliveryUnitLoading">
              <el-option v-for="(item, index) in F_DeliveryUnitOptions" :key="index" :label="item.F_FullName"
                :value="item.F_Id" :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="hasFormPermission('F_ApplicationPurposes')">
          <el-form-item label="申请用途" prop="F_ApplicationPurposes">
            <el-input v-model="formData['F_ApplicationPurposes']" placeholder="请输入申请用途"
              :disabled="hasDisabledPermission('F_ApplicationPurposes',false)"
              :readonly="!hasEditPermission('F_ApplicationPurposes',false)" clearable
              :style="{width: '100%'}"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="hasFormPermission('F_DeliveryDate')">
          <el-form-item label="交货日期" prop="F_DeliveryDate">
            <el-date-picker :disabled="hasDisabledPermission('F_DeliveryDate',false)"
              :readonly="!hasEditPermission('F_DeliveryDate',false)" v-model="formData['F_DeliveryDate']"
              format="yyyy-MM-dd" value-format="yyyy-MM-dd" :style="{width: '100%'}" placeholder="请选择交货日期"
              clearable></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="hasFormPermission('F_BudgetAmount')">
          <el-form-item label="预算金额" prop="F_BudgetAmount">
            <el-input v-model="formData['F_BudgetAmount']" placeholder="请输入预算金额"
              :disabled="hasDisabledPermission('F_BudgetAmount',false)"
              :readonly="!hasEditPermission('F_BudgetAmount',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="hasFormPermission('F_ActualAmount')">
          <el-form-item label="实际金额" prop="F_ActualAmount">
            <el-input v-model="formData['F_ActualAmount']" placeholder="请输入实际金额"
              :disabled="hasDisabledPermission('F_ActualAmount',false)"
              :readonly="!hasEditPermission('F_ActualAmount',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="hasFormPermission('F_Emergencylevel')">
          <el-form-item label="紧急程度" prop="F_Emergencylevel">
            <el-select v-model="formData['F_Emergencylevel']" placeholder="请选择紧急程度"
              :disabled="hasDisabledPermission('F_Emergencylevel',false)"
              :readonly="!hasEditPermission('F_Emergencylevel',undefined)" filterable clearable
              :style="{width: '100%'}">
              <el-option v-for="(item, index) in F_EmergencylevelOptions" :key="index"
                :label="item.F_ItemName" :value="item.F_ItemValue" :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <avue-form v-loading="preloadLoading119" element-loading-text="数据预加载中..."
            element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.7)"
            :option="option119" v-model="erp_purchaserequsetentry" :disabled="disabled">
            <template slot-scope="{row}" slot="input">
              <el-tag>{{row}}</el-tag>
            </template>
          </avue-form>
        </el-col>
        <el-col :span="24" v-if="hasFormPermission('F_Description')">
          <el-form-item label="备注" prop="F_Description">
            <el-input v-model="formData['F_Description']" type="textarea" placeholder="请输入备注"
              :disabled="hasDisabledPermission('F_Description',false)"
              :readonly="!hasEditPermission('F_Description',false)" :autosize="{minRows: 4, maxRows: 4}"
              :style="{width: '100%'}"></el-input>
          </el-form-item>
        </el-col>
       <el-col :span="12" v-if="hasFormPermission('F_DocumentStatus')" hidden="hidden">
          <el-form-item label="审核状态" prop="F_DocumentStatus">
            <el-input v-model="formData['F_DocumentStatus']" placeholder="请输入审核状态"
              :disabled="hasDisabledPermission('F_DocumentStatus',true)"
              :readonly="!hasEditPermission('F_DocumentStatus',false)" clearable
              :style="{width: '100%'}"></el-input>
          </el-form-item>
        </el-col>
         <!-- <el-col :span="12" v-if="hasFormPermission('F_InvalidMark')">
          <el-form-item label="状态" prop="F_InvalidMark">
            <el-input v-model="formData['F_InvalidMark']" placeholder="请输入状态"
              :disabled="hasDisabledPermission('F_InvalidMark',true)"
              :readonly="!hasEditPermission('F_InvalidMark',true)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col> -->
        <el-col :span="12" v-if="hasFormPermission('F_CreatorUserId')">
          <el-form-item label="制单人员" prop="F_CreatorUserId" required>
            <avue-information-body :operationVal="operationVal" infoType='user'
              :whetherToRebindSecondaryEditing='false' v-model="formData['F_CreatorUserId']"
              placeholder="当前用户制单人员" :disabled="hasDisabledPermission('F_CreatorUserId',true)"
              :readonly="!hasEditPermission('F_CreatorUserId',true)" :style="{width: '100%'}">
            </avue-information-body>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="hasFormPermission('F_CreatorTime')">
          <el-form-item label="制单时间" prop="F_CreatorTime">
            <el-date-picker :disabled="hasDisabledPermission('F_CreatorTime',false)"
              :readonly="!hasEditPermission('F_CreatorTime',false)" v-model="formData['F_CreatorTime']"
              format="yyyy-MM-dd" value-format="yyyy-MM-dd" :style="{width: '100%'}" placeholder="请选择制单时间"
              clearable></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="!isWorkflowForm">
          <el-form-item size="large" v-if="isEdit">
            <el-button type="primary" @click="tableExamine">审核</el-button>
            <el-button type="primary" @click="submitForm">提交</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-col>
        <avue-filterable-data-list :conf="autoCompleteConf" v-if="autoCompleteDialogVisible"
          v-on:onHandler="filterableCallBack"></avue-filterable-data-list>
      </el-form>
    </el-row>
  </div>
</template>
<script>

        import FilterableDataList from '@/components/generator/clientComponents/FilterableDataList.vue';
        import workflowFormAuthorize from "@/mixins/workflowFormAuthorize";
        import authorizeMixin from "@/mixins/authorize";
        import { baseUrl } from "@/config/env";
        import request from "@/router/axios";
        export default {
          mixins: [authorizeMixin,workflowFormAuthorize],
       
  components: {},
  props: ['keyValue', 'isEdit', 'disabled'],
  data() {
    let _this = this
    return {
      showForm: true,
      operationVal: 'add',
      isAdd: true,
      addressUrl:'erp_purchaserequsetinfo2',
      mainTableName: 'erp_purchaserequset',
      formConfig: {
        "fields": [{
          "__vModel__": "F_DocunNumber",
          "__config__": {
            "label": "单据编号",
            "showLabel": true,
            "tag": "el-input",
            "avueType": "autoCode",
            "span": 8,
            "autoCodeRule": "DocunNumber",
            "formId": 104
          }
        }, {
          "tempType": "date",
          "__vModel__": "F_DocumentDate",
          "__config__": {
            "label": "单据日期",
            "tag": "el-date-picker",
            "avueType": "datetime",
            "showLabel": true,
            "span": 8,
            "formId": 107
          }
        }, {
          "__vModel__": "F_ChargePeople",
          "__config__": {
            "label": "经办人员",
            "showLabel": true,
            "tag": "el-input",
            "avueType": "input",
            "span": 8,
            "formId": 106
          }
        }, {
          "__vModel__": "F_DeliveryUnit",
          "__config__": {
            "label": "供货单位",
            "showLabel": true,
            "tag": "el-select",
            "avueType": "asso-select",
            "filterable": true,
            "span": 8,
            "dataType": "dataSql",
            "autoBindFields": "",
            "formId": 112,
            "database": "localDB",
            "sql": "\tselect i.F_Id,F_FullName from erp_inoutunit i where i.F_UniType=1",
            "showField": "F_FullName",
            "saveField": "F_Id"
          }
        }, {
          "__vModel__": "F_ApplicationPurposes",
          "__config__": {
            "label": "申请用途",
            "showLabel": true,
            "tag": "el-input",
            "avueType": "input",
            "span": 8,
            "formId": 109
          }
        }, {
          "tempType": "date",
          "__vModel__": "F_DeliveryDate",
          "__config__": {
            "label": "交货日期",
            "tag": "el-date-picker",
            "avueType": "datetime",
            "showLabel": true,
            "span": 8,
            "formId": 113
          }
        }, {
          "__vModel__": "F_BudgetAmount",
          "__config__": {
            "label": "预算金额",
            "showLabel": true,
            "tag": "el-input",
            "avueType": "input",
            "span": 8,
            "formId": 114
          }
        }, {
          "__vModel__": "F_ActualAmount",
          "__config__": {
            "label": "实际金额",
            "showLabel": true,
            "tag": "el-input",
            "avueType": "input",
            "span": 8,
            "formId": 115
          }
        }, {
          "__vModel__": "F_Emergencylevel",
          "__config__": {
            "label": "紧急程度",
            "showLabel": true,
            "tag": "el-select",
            "avueType": "select",
            "span": 8,
            "formId": 117,
            "dataType": "dataItem",
            "dataItem": "Degree"
          }
        }, {
          "tempType": "default",
          "__config__": {
            "componentName": "table",
            "componentTitle": "商品信息",
            "layoutTree": true,
            "dataType": "dataSql",
            "span": 24,
            "formId": 119,
            "children": [
              {
              "__vModel__": "F_GoodsId",
              "__config__": {
                "label": "商品ID",
                "showLabel": true,
                "tag": "el-input",
                "avueType": "input",
                "span": 8,
                "bindTable": "erp_purchaserequsetentry",
                "bindTableField": "F_Id"
              }
            },
              {
              "__vModel__": "F_GoodsName",
              "__config__": {
                "label": "商品名称",
                "showLabel": true,
                "tag": "el-input",
                "avueType": "input",
                "span": 8,
                "bindTable": "erp_purchaserequsetentry",
                "bindTableField": "F_GoodsName"
              }
            }, {
              "__vModel__": "F_GoodCode",
              "__config__": {
                "label": "商品编号",
                "showLabel": true,
                "tag": "el-input",
                "avueType": "input",
                "span": 8,
                "bindTable": "erp_purchaserequsetentry",
                "bindTableField": "F_GoodCode"
              }
            }, {
              "__vModel__": "F_Specs",
              "__config__": {
                "label": "规格型号",
                "showLabel": true,
                "tag": "el-input",
                "avueType": "input",
                "span": 8,
                "bindTable": "erp_purchaserequsetentry",
                "bindTableField": "F_Specs"
              }
            }, 
            {
              "__vModel__": "F_UnitId",
              "__config__": {
                "label": " 单位",
                "showLabel": true,
                "tag": "el-select",
                "avueType": "select",
                "span": 8,
                "bindTable": "erp_purchaseorderentry",
                "bindTableField": "F_UnitId",
                "dataType": "dataItem",
                "dataItem": "入库单位"
              }
            },
            , {
              "__vModel__": "F_Quantity",
              "__config__": {
                "label": "数量",
                "showLabel": true,
                "tag": "el-input-number",
                "avueType": "number",
                "span": 8,
                "bindTable": "erp_purchaserequsetentry",
                "bindTableField": "F_Quantity"
              }
            }, {
              "tempType": "number",
              "__vModel__": "F_UnitPrice",
              "computationalConfiguration": [],
              "prepend": "¥",
              "__config__": {
                "label": "价格",
                "showLabel": true,
                "tag": "el-input",
                "avueType": "input",
                "span": 8,
                "bindTable": "erp_purchaserequsetentry",
                "bindTableField": "F_UnitPrice"
              }
            }, {
              "tempType": "number",
              "__vModel__": "F_Amount",
              "computationalConfiguration": [],
              "prepend": "¥",
              "__config__": {
                "label": "金额",
                "showLabel": true,
                "tag": "el-input",
                "avueType": "input",
                "span": 8,
                "bindTable": "erp_purchaserequsetentry",
                "bindTableField": "F_Amount"
              }
            }, {
              "__vModel__": "F_Des",
              "__config__": {
                "label": "说明信息",
                "showLabel": true,
                "tag": "el-input",
                "avueType": "input",
                "span": 8,
                "bindTable": "erp_purchaserequsetentry",
                "bindTableField": "F_Des"
              }
            }],
            "database": "localDB",
            "sql": "select g.F_Id,g.F_FullName,g.F_EnCode,g.F_Specs,g.F_InUnit,g.F_SalePrice,g.F_CostPrice from \terp_goods g"
          }
        }, {
          "tempType": "textarea",
          "__vModel__": "F_Description",
          "__config__": {
            "label": "备注",
            "showLabel": true,
            "tag": "el-input",
            "avueType": "textarea",
            "span": 24,
            "formId": 128
          }
        }, {
          "__vModel__": "F_DocumentStatus",
          "__config__": {
            "label": "审核状态",
            "showLabel": true,
            "tag": "el-input",
            "avueType": "input",
            "span": 12,
            "formId": 131
          }
        }, {
          "__vModel__": "F_InvalidMark",
          "__config__": {
            "label": "状态",
            "showLabel": true,
            "tag": "el-input",
            "avueType": "input",
            "span": 12,
            "formId": 132
          }
        }, {
          "__vModel__": "F_CreatorUserId",
          "__type__": "info",
          "infoType": "user",
          "__organize__": true,
          "__config__": {
            "label": "制单人员",
            "showLabel": true,
            "tag": "avue-information-body",
            "span": 12,
            "whetherToRebindSecondaryEditing": false,
            "formId": 129,
            "placeholder": "当前用户"
          }
        }, {
          "tempType": "date",
          "__vModel__": "F_CreatorTime",
          "__config__": {
            "label": "制单时间",
            "tag": "el-date-picker",
            "avueType": "datetime",
            "showLabel": true,
            "span": 12,
            "formId": 130
          }
        }]
      },
      autoCompleteDialogVisible: false,
      autoCompleteConf: {},
      formData: {
        'F_DocunNumber': '',
        'F_DocumentDate': null,
        'F_ChargePeople': '',
        'F_DeliveryUnit': '',
        'F_ApplicationPurposes': '',
        'F_DeliveryDate': null,
        'F_BudgetAmount': '',
        'F_ActualAmount': '',
        'F_Emergencylevel': '',
        'F_Description': '',
        'F_DocumentStatus': "1",
        'F_InvalidMark': "1",
        'F_CreatorUserId': '',
        'F_CreatorTime': null,
      },
      rules: {
        F_DocunNumber: [{
          required: true,
          message: '单据编号',
          trigger: 'blur'
        }],
        F_DocumentDate: [{
          required: true,
          message: '请选择单据日期',
          trigger: 'change'
        }],
        F_ChargePeople: [{
          required: true,
          message: '请输入经办人员',
          trigger: 'blur'
        }],
        F_BudgetAmount: [{
          required: true,
          message: '请输入预算金额',
          trigger: 'blur'
        }],
         F_ActualAmount: [{
          required: true,
          message: '请输入实际金额',
          trigger: 'blur'
        }],
        F_DeliveryUnit: [{
          required: true,
          message: '请选择供货单位',
          trigger: 'change'
        }],
        F_ApplicationPurposes: [{
          required: true,
          message: '请输入申请用途',
          trigger: 'blur'
        }],
        F_DeliveryDate: [{
          required: true,
          message: '请选择交货日期',
          trigger: 'change'
        }],
        F_Emergencylevel: [],
        F_Description: [],
        F_DocumentStatus: [{
          required: true,
          message: '请输入审核状态',
          trigger: 'blur'
        }],
        F_InvalidMark: [{
          required: true,
          message: '请输入状态',             
          trigger: 'blur'
        }],
        F_CreatorTime: [],
      },
      F_DeliveryUnitOptions: [],
      F_DeliveryUnitLoading: false,
      F_EmergencylevelOptions: [],
      option119: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 100,
        addBtn:false,
        delBtn : false,
        disabled: !':disabled="disabled"',
        column: [{
          label: '商品信息',
          prop: 'erp_purchaserequsetentry',
          type: 'dynamic', 
          span: 24,
          children: {
            align: 'center',
            headerAlign: 'center',
            rowAdd: (done) => {
              // this.$message.success('新增回调');
              done({});
            },
            rowDel: (row, done) => {
              // this.$message.success('删除回调'+JSON.stringify(row));
              done();
            },
            column: [
              {
              label: '商品ID',
              prop: 'F_GoodsId',
              hide:true,
              type: 'input',
            },
              {
              label: '商品名称',
              prop: 'F_GoodsName',
              type: 'input',
            }, {
              label: '商品编号',
              prop: 'F_GoodCode',
              type: 'input',
            }, {
              label: '规格型号',
              prop: 'F_Specs',
              type: 'input',
            },
               {
              label: '单位',
              prop: 'F_UnitId',
               disabled:true,
              type: 'select',
                props: {
                  label: 'F_FullName',
                value: 'F_Id'
              },
               dicUrl:  baseUrl + '/erp_purchaserequsetinfo2/unit' 
            },
             {
              label: '数量',
              prop: 'F_Quantity',
              type: 'number',
            }, {
              label: '价格',
              prop: 'F_UnitPrice',
              type: 'input',
            }, {
              label: '金额',
              prop: 'F_Amount',
              type: 'input',
            }, {
              label: '说明信息',
              prop: 'F_Des',
              type: 'input',
            }, ]
          }
        }, ],
      },
      erp_purchaserequsetentry: {},
      preloadLoading119: false,
    }
  },
  computed: {},
  watch: {
    erp_purchaserequsetentry:{
      handler(){
        this.erp_purchaserequsetentry.erp_purchaserequsetentry.map(item=>{
          item.F_Amount=item.F_Quantity*item.F_UnitPrice;
        })
      },
      immediate:true,
      deep :true
    }

  },
  created() {},
  async mounted() {
    //TODO   再这里做数据回填 请求表单数据
   
           if(this.keyValue){
              this.isAdd = false;
          }
           if(!this.isAdd&&this.keyValue){
              this.operationVal = 'edit';
              this.showForm = false;
              try {
                let res = await request({
                  url: baseUrl + "/"+this.addressUrl+"/" + this.keyValue,
                  method: "get",
                });
                  
            this.formData = res.data.data.erp_purchaserequset
            
          this.erp_purchaserequsetentry.erp_purchaserequsetentry = res.data.data.erp_purchaserequsetentry
          
        this.erp_purchaserequsetentry.erp_purchaserequsetentry.forEach(element => {
      });
      
                  this.showForm = true;
              } catch (error) {
                
              }
          }

       
    if (typeof this.getF_DocunNumberOptions == "function") {
      await this.getF_DocunNumberOptions();
    }
    if (typeof this.getF_DeliveryUnitOptions == "function") {
      await this.getF_DeliveryUnitOptions();
    }
    if (typeof this.getF_EmergencylevelOptions == "function") {
      await this.getF_EmergencylevelOptions();
    }
    if (this.isAdd) {
      await this.preloadData119()
    }
  },
  methods: {
    getFormData() {
      let key = this.mainTableName + 'Entity';
      let returnParams = {};
      
      returnParams[key] = this.formData;
      console.log(this.formData.fid);
      return {
        ...returnParams,
        erp_purchaserequsetentryEntityList: this.erp_purchaserequsetentry.erp_purchaserequsetentry,
      };
    },
    tableExamine()
    {
      if(this.formData.F_DocumentStatus==2)
      {
          this.$confirm("改采购申请单已审核通过，请勿重复操作");
          return;
      }
      let key = this.mainTableName + 'Entity';
      let returnParams = {};
      
      returnParams[key] = this.formData;
      console.log(this.formData.fid);
      let newObj= {
        ...returnParams,
        id:this.formData.fid,
        erp_purchaserequsetentryEntityList: this.erp_purchaserequsetentry.erp_purchaserequsetentry,
      };
       
      console.log(111);
           request({
            url: baseUrl + "/"+this.addressUrl+ "/"+"examine"+"/"+newObj.id,
            method: "post",
            data : newObj
          }).then((res) => {

            this.$notify({
              title: "成功",
              message: "审核成功",
              type: "success",
            });
             this.$emit("onChange",true)
          });

    },
    submitForm() {

      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        this.erp_purchaserequsetentry.erp_purchaserequsetentry.forEach(element => {});
        //格式化数据
        let newObj = this.getFormData();
        
        //如果没有传入参数就是新增
        if (!this.keyValue) {

          request({
            url: baseUrl + "/"+this.addressUrl,
            method: "post",
            data : newObj
          }).then((res) => {

            this.$notify({
              title: "成功",
              message: "新增成功",
              type: "success",
            });
             this.$emit("onChange",true)
          });

        }
        else{

         request({
            url: baseUrl + "/"+this.addressUrl+"/" + this.keyValue,
            method: "put",
            data : newObj
          }).then((res) => {

            this.$notify({
              title: "成功",
              message: "修改成功",
              type: "success",
            });
             this.$emit("onChange",true)
          });

        }
       
       
        
      })
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
    },
    formatTree(data, valueField, lableField, childField, type) {
      let tree = [];
      data.forEach((node, index) => {
        let newNode = {
          value: node[valueField],
          label: node[lableField],
        };
        if (type) {
          newNode.disabled = node[valueField] == undefined ? true : false
        }
        tree.push(newNode);
        if (node[childField] != null && node[childField].length > 0) {
          newNode.children = (this.formatTree(node[childField], valueField, lableField, childField,
          type));
        }
      }, this);
      return tree;
    },
    
          //辅助工作流 审批(编辑) 预留方法
          handleEdit() {
          },
          
    filterableCallBack(data) {
      if (!this.autoCompleteConf) {
        return false;
      }
      //弹窗关闭前回填数据  如果有选择数据项
      if (data) {
        let fields = this.getElements(this.formConfig.fields);
        let autoBindFields = JSON.parse(this.autoCompleteConf.autoBindFields) || {};
        let saveField = this.autoCompleteConf.dataType == 'dataItem' ? 'F_ItemValue' : this.autoCompleteConf
          .saveField
        this.setModelValue(this.formConfig.fields, autoBindFields, data);
        //自己赋值
        if (this.autoCompleteConf.dataType == 'dataItem') {
          for (let i = 0; i < fields.length; i++) {
            if (fields[i].__config__.formId == this.autoCompleteConf.formId) {
              this.formData[this.autoCompleteConf.model] = data[saveField];
              break;
            }
          }
        }
        else {
          this.formData[this.autoCompleteConf.model] = data[saveField];
        }
      }
      //更新表单校验
      this.$refs['elForm'].validate(valid => {
        console.log('更新表单校验 valid', valid);
      })
      //关闭弹窗
      this.autoCompleteDialogVisible = false;
    },
    setModelValue(fields, autoBindFields, data) {
      fields.map(item => {
        if (item.__config__.componentName && item.__config__.componentName == 'avue-tabs') {
          let childrenObj = item.__config__.childrenObj || {};
          for (let key in childrenObj) {
            let children = childrenObj[key];
            this.setModelValue(children, autoBindFields, data);
          }
        }
        else {
          if (autoBindFields.hasOwnProperty(item.__config__.formId)) {
            this.formData[item.__vModel__] = data[autoBindFields[item.__config__.formId]];
          }
        }
      });
    },
    getElements(fields) {
      let _arr = [];
      fields.map(item => {
        if (item.__config__.componentName == 'avue-tabs') {
          let childrenObj = item.__config__.childrenObj || {};
          for (let key in childrenObj) {
            _arr.push(...this.getElements(childrenObj[key]));
          }
        }
        else {
          _arr.push(item);
        }
      });
      return (() => {
        return _arr;
      })();
    },
    async getF_DocunNumberOptions() {
      // 注意：this.$axios是通过Vue.prototype.$axios = axios挂载产生的
      if (!this.isAdd) { //如果是编辑 不用请求
        return;
      }
      try {
        let resp = await this.$axios({
          method: 'get',
          url:  baseUrl + '/code-rules/DocunNumber/gen',
        });
        if (resp.data.data) {
          this.formData.F_DocunNumber = resp.data.data;
        }
      }
      catch (error) {}
    },
    async getF_DeliveryUnitOptions(query) {
      // 注意：this.$axios是通过Vue.prototype.$axios = axios挂载产生的
      let keyword = ' ';
      if (query) {
        keyword = query;
      }
      if (query !== '') {
        this.F_DeliveryUnitOptionsLoading = true;
      }
      try {
        if ('dataSql' == 'dataSource') {
          let resp = await
          this.$axios({
            method: 'get',
            url:  baseUrl + '/data-sources/undefined/data/?field=F_FullName&keyword=' +
              keyword
          });
          this.F_DeliveryUnitOptionsLoading = false;
          this.F_DeliveryUnitOptions = resp.data.data;
        }
        else {
          let params = {};
          params.sql = `	select i.F_Id,F_FullName from erp_inoutunit i where i.F_UniType=1`;
          let resp = await
          this.$axios({
            method: 'get',
            params: params,
            url:  baseUrl + '/database-links/localDB/datas'
          });
          this.F_DeliveryUnitOptionsLoading = false;
          this.F_DeliveryUnitOptions = resp.data.data;
        }
      }
      catch (error) {}
    },
    handlerSelectF_DeliveryUnit(val) {
      let autoBindFields = JSON.parse('[]');
      let fields = this.formConfig.fields
      let saveField = 'dataSql' == 'dataItem' ? 'F_ItemValue' : 'F_Id'
      //得对应数据列
      let data = this.F_DeliveryUnitOptions.filter(item => {
        return item[saveField] == val;
      })[0];
      if (!data) {
        return;
      }
      //数据回显
      this.setModelValue(this.formConfig.fields, autoBindFields, data);
    },
    async getF_EmergencylevelOptions() {
      // 注意：this.$axios是通过Vue.prototype.$axios = axios挂载产生的
      try {
        let resp = await this.$axios({
          method: 'get',
          url:  baseUrl + '/data-items/Degree/detail',
        });
        if (resp.data.data) {
          this.F_EmergencylevelOptions = resp.data.data;
        }
      }
      catch (error) {}
    },
    async preloadData119() {
      
      //编辑时 取消预加载
      if (this.keyValue) return;
      this.preloadLoading119 = true;
      // 注意：this.$axios是通过Vue.prototype.$axios = axios挂载产生的
      try {
        let resp = await this.$axios({
          method: 'get',
          url:  baseUrl + '/database-links/localDB/datas',
          params: {
            sql: 'select g.F_Id,g.F_FullName,g.F_EnCode,1 as F_Quantity,g.F_SalePrice as F_Amount,g.F_Specs,g.F_InUnit,c.F_FullName as UnitName,g.F_CostPrice from 	erp_goods g left join erp_unitconvert c on g.F_InUnit=c.F_Id'
          }
        });
         
        if (resp.data) {
          let {
            data
          } = resp.data
          let dynamic = this.getDicData(data,
            '{"F_GoodsId":"F_Id","F_GoodsName":"F_FullName","F_GoodCode":"F_EnCode","F_Specs":"F_Specs","F_UnitId":"F_InUnit","F_Quantity":"F_Quantity","F_UnitPrice":"F_CostPrice","F_Amount":"F_Amount","F_Des":""}'
            );
            
          this.erp_purchaserequsetentry.erp_purchaserequsetentry = dynamic;
          this.preloadLoading119 = false;
        }
      }
      catch (error) {}
    },
    getDicData(arr, prestrainFieldsConf) {
      let resultArr = [];
      prestrainFieldsConf = JSON.parse(prestrainFieldsConf) || {};
      arr.map(item => {
        let _obj = {};
        for (let key in prestrainFieldsConf) {
          _obj[key] = item[prestrainFieldsConf[key]];
        }
        resultArr.push(_obj);
      });
      return resultArr;
    },
  }
}

</script>
<style>
.el-table__empty-block {
  width: 100% !important;
}

.avue-form__row {
  padding: 0 !important;
}

</style>
